import { data, redirect, useActionData, useFetcher, useLoaderData } from "react-router";
// import { getSession } from "~/session.server";
import type { Route } from "./+types/session-test";
import { Button } from "~/components/ui/button";
import { parse } from "cookie";
import { useEffect } from "react";
/* export const loader = async (params: Route.LoaderArgs) => {
  const { request } = params
  const session = await getSession(request.headers.get("Cookie"));
  console.log('when session test page loader, has auth ', session.has('auth'),'. auth is', session.get('auth'));

  return {
    message: "Hello, world!",
    session
  }
} */
export const loader = async (params: Route.LoaderArgs) => {
  const { request } = params
  const session = parse(request.headers.get("Cookie") ?? '');
  console.log('session is', JSON.stringify(session));
  
  console.log('when session test page loader, has auth ', session.auth ? 'true' : 'false', '. auth is', session.auth);

  return {
    message: "Hello, world!",
    session
  }
}

/* 
export const action = async (params: Route.ActionArgs) => {
  const { request } = params
  const session = await getSession(request.headers.get("Cookie"));
  session.set('auth', '123456');
  return data({ message: "登录成功" }, {
    headers: { 'Set-Cookie': await commitSession(session) }
  })
}
 */
export default function SessionTest() {
  const { session } = useLoaderData<typeof loader>();
  const fetcher = useFetcher()
  useEffect(()=>{
    console.log(document.cookie );
    console.log('session is', JSON.stringify(session));
  },[session])
  // const data = useActionData<typeof action>()
  return <fetcher.Form method="post" action="/session-test" className="flex flex-col gap-2" >
    {/* {data?.message} */}
    <Button formAction="/login" formMethod="post" type="submit">submit login</Button>
    <Button formAction="/logout" formMethod="post" type="submit">submit logout</Button>
  </fetcher.Form>;
}